package controllers

import (
	"database/sql"
	//	"fmt"
	"html/template"
	"log"
	"net/http"

	_ "github.com/Go-SQL-Driver/MySQL"
)

type Good struct {
	GoodsId    int
	Price      float64
	GoodName   string
	GoodImg    string
	Goodstatus int
}

func GoodsAll(w http.ResponseWriter, r *http.Request) {
	goods := []Good{}
	log.Printf("goodsAll")
	db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/demo?charset=utf8")
	checkErr(err)
	rows, _ := db.Query("SELECT goodsId,price,goodName,goodimg,goodstatus From goods")
	goodsId := 0
	price := 0.0
	goodNmae := ""
	goodimg := ""
	goodstatus := 1
	for rows.Next() {
		rows.Scan(&goodsId, &price, &goodNmae, &goodimg, &goodstatus)
		//		fmt.Println(goodsId, price, goodNmae, goodimg)
		g := Good{goodsId, price, goodNmae, goodimg, goodstatus}
		goods = append(goods, g)

	}
	//	fmt.Printf("gs %d", goods)
	defer db.Close()
	tmpl, _ := template.ParseFiles("views/goodsshow.html")
	tmpl.Execute(w, struct{ Goods []Good }{goods})

}
func checkErr(err error) {
	log.Printf("checkErr")
	if err != nil {
		panic(err)
	}
}

//https://www.cnblogs.com/tsiangleo/p/4483657.html
func Delgood(w http.ResponseWriter, r *http.Request) {
	goods := []Good{}
	log.Printf("Delgood")
	db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/demo?charset=utf8")
	checkErr(err)
	id := r.FormValue("id")
	status := r.FormValue("status")
	db.Exec("UPdate  goods set goodstatus = ? WHERE goodsId = ?", status, id)
	rows, _ := db.Query("SELECT goodsId,price,goodName,goodimg,goodstatus From goods")
	goodsId := 0
	price := 0.0
	goodNmae := ""
	goodimg := ""
	goodstatus := 0
	for rows.Next() {
		rows.Scan(&goodsId, &price, &goodNmae, &goodimg, &goodstatus)
		//		fmt.Println(goodsId, price, goodNmae, goodimg)
		g := Good{goodsId, price, goodNmae, goodimg, goodstatus}
		goods = append(goods, g)

	}
	//	fmt.Printf("gs %d", goods)
	defer db.Close()
	tmpl, _ := template.ParseFiles("views/goodsshow.html")
	tmpl.Execute(w, struct{ Goods []Good }{goods})

}

func Addgood(w http.ResponseWriter, r *http.Request) {
	goods := []Good{}
	log.Printf("Addgood")
	db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/demo?charset=utf8")
	checkErr(err)
	iprice := r.FormValue("price")
	igoodName := r.FormValue("goodName")
	igoodimg := r.FormValue("goodimg")
	istatus := r.FormValue("status")
	db.Exec("INSERT INTO  goods(price,goodName,goodimg,goodstatus) values(?,?,?,?)", iprice, igoodName, igoodimg, istatus)
	rows, _ := db.Query("SELECT goodsId,price,goodName,goodimg,goodstatus From goods")
	goodsId := 0
	price := 0.0
	goodNmae := ""
	goodimg := ""
	goodstatus := 0
	for rows.Next() {
		rows.Scan(&goodsId, &price, &goodNmae, &goodimg, &goodstatus)
		//		fmt.Println(goodsId, price, goodNmae, goodimg)
		g := Good{goodsId, price, goodNmae, goodimg, goodstatus}
		goods = append(goods, g)

	}
	//	fmt.Printf("gs %d", goods)
	defer db.Close()
	tmpl, _ := template.ParseFiles("views/goodsshow.html")
	tmpl.Execute(w, struct{ Goods []Good }{goods})

}
